"""
系统配置文件
"""

import yaml
import os
from dataclasses import dataclass
from typing import Dict, List, Any

@dataclass
class DetectionConfig:
    """车辆检测配置"""
    model_path: str = "models/yolo_obb.pt"
    input_size: int = 640
    confidence_threshold: float = 0.6
    nms_threshold: float = 0.4
    max_detections: int = 100
    use_gpu: bool = True

@dataclass
class TrackingConfig:
    """多目标跟踪配置"""
    track_buffer: int = 30
    match_threshold: float = 0.8
    frame_rate: int = 25
    reid_dim: int = 512
    max_age: int = 30
    min_hits: int = 3

@dataclass
class IntentConfig:
    """意图识别配置"""
    min_trajectory_length: int = 10
    direction_weight: float = 0.4
    heading_weight: float = 0.3
    proximity_weight: float = 0.2
    speed_weight: float = 0.1
    intent_threshold: float = 0.7
    exit_regions: List = None

@dataclass
class QueueConfig:
    """排队分析配置"""
    speed_threshold: float = 0.3  # m/s
    duration_threshold: int = 20  # 秒
    cluster_eps: float = 15.0  # 米
    min_samples: int = 2
    longitudinal_weight: float = 0.6
    lateral_weight: float = 0.2
    euclidean_weight: float = 0.2

@dataclass
class GeometryConfig:
    """几何计算配置"""
    centerline_points: List = None
    stop_line_position: List = None
    camera_matrix: List = None
    dist_coeffs: List = None
    pixel_to_meter_ratio: float = 0.1

@dataclass
class PredictionConfig:
    """预测模型配置"""
    history_length: int = 60
    prediction_horizon: int = 30
    hidden_dim: int = 256
    num_layers: int = 3
    dropout_rate: float = 0.2
    num_heads: int = 8
    learning_rate: float = 0.001
    model_path: str = "models/predictor.pth"

class SystemConfig:
    """系统总配置"""
    
    def __init__(self, config_path="config.yaml"):
        self.config_path = config_path
        self.load_config()
        
    def load_config(self):
        """从YAML文件加载配置"""
        if os.path.exists(self.config_path):
            with open(self.config_path, 'r', encoding='utf-8') as f:
                config_data = yaml.safe_load(f)
        else:
            config_data = self.get_default_config()
            
        # 初始化各模块配置
        self.detection = DetectionConfig(**config_data.get('detection', {}))
        self.tracking = TrackingConfig(**config_data.get('tracking', {}))
        self.intent = IntentConfig(**config_data.get('intent', {}))
        self.queue = QueueConfig(**config_data.get('queue', {}))
        self.geometry = GeometryConfig(**config_data.get('geometry', {}))
        self.prediction = PredictionConfig(**config_data.get('prediction', {}))
        
    def get_default_config(self):
        """获取默认配置"""
        return {
            'detection': {
                'model_path': 'models/yolo_obb.pt',
                'input_size': 640,
                'confidence_threshold': 0.6,
                'nms_threshold': 0.4,
                'max_detections': 100,
                'use_gpu': True
            },
            'tracking': {
                'track_buffer': 30,
                'match_threshold': 0.8,
                'frame_rate': 25,
                'reid_dim': 512,
                'max_age': 30,
                'min_hits': 3
            },
            'intent': {
                'min_trajectory_length': 10,
                'direction_weight': 0.4,
                'heading_weight': 0.3,
                'proximity_weight': 0.2,
                'speed_weight': 0.1,
                'intent_threshold': 0.7,
                'exit_regions': [[100, 200], [150, 250], [200, 300]]
            },
            'queue': {
                'speed_threshold': 0.3,
                'duration_threshold': 20,
                'cluster_eps': 15.0,
                'min_samples': 2,
                'longitudinal_weight': 0.6,
                'lateral_weight': 0.2,
                'euclidean_weight': 0.2
            },
            'geometry': {
                'centerline_points': [[0, 0], [50, 10], [100, 20], [150, 30]],
                'stop_line_position': [160, 35],
                'pixel_to_meter_ratio': 0.1
            },
            'prediction': {
                'history_length': 60,
                'prediction_horizon': 30,
                'hidden_dim': 256,
                'num_layers': 3,
                'dropout_rate': 0.2,
                'num_heads': 8,
                'learning_rate': 0.001,
                'model_path': 'models/predictor.pth'
            }
        }
    
    def save_config(self, path=None):
        """保存配置到文件"""
        save_path = path or self.config_path
        config_data = {
            'detection': self.detection.__dict__,
            'tracking': self.tracking.__dict__,
            'intent': self.intent.__dict__,
            'queue': self.queue.__dict__,
            'geometry': self.geometry.__dict__,
            'prediction': self.prediction.__dict__
        }
        
        with open(save_path, 'w', encoding='utf-8') as f:
            yaml.dump(config_data, f, default_flow_style=False, allow_unicode=True)